using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteAlways]
[RequireComponent(typeof(Camera))]
public class OrthoFlexCamera : MonoBehaviour
{
    [SerializeField]
    private float startY;
    [Range(0, 1)]
    [SerializeField]
    private float offsetY;
    private Camera orthoCamera;

    // Start is called before the first frame update
    void Awake()
    {
        TryGetComponent<Camera>(out orthoCamera);
        UpdateCameraPos();
    }

    void UpdateCameraPos()
    {
        if (orthoCamera == null) return;
        var y = startY - orthoCamera.orthographicSize * 2 * offsetY;
        var pos = orthoCamera.transform.position;
        pos.y = y;
        orthoCamera.transform.position = pos;
    }

#if UNITY_EDITOR
    private float lastRatio;
    // Update is called once per frame
    void Update()
    {
        if (Mathf.Approximately(lastRatio, orthoCamera.aspect))
            return;

        lastRatio = orthoCamera.aspect;
        OnValidate();
    }

    void OnValidate()
    {
        UpdateCameraPos();
    }
#endif
}
